package com.xxkk.spring_boot_web.sdk.adjPay;

import com.google.gson.Gson;
import com.xxkk.spring_boot_web.utils.MD5Util;
import com.xxkk.spring_boot_web.utils.SignTool;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class adjPaySdk {
    private static final Logger log = Logger.getLogger(adjPaySdk.class);

    /**
     * key=val&key2=val
     *
     * @param map ,
     * @return key=val&key2=val 过滤str == null || str.trim().isEmpty();
     */
    private static String get_ori_sign(Map<String, Object> map) {
        TreeMap<String, Object> treeMap = new TreeMap<>(map);
        StringBuilder sb = new StringBuilder();
        Set<String> keys = treeMap.keySet();
        for (String key : keys) {
            Object value = treeMap.get(key);
            if (value == null || "".equals(value))
                continue;
            sb.append(key).append("=").append(value).append("&");
        }
//        sb.deleteCharAt(sb.length() - 1);// del the end of "&" //cancel
        return sb.toString();
    }

    /**
     * adjPay 签名算法
     *
     * @return sign
     */
    public static String getSign(Map<String, Object> map, String privateKey) {
        map.remove("sign");
        String sign = get_ori_sign(map);
        sign += "key=" + privateKey;
        try {
            return MD5Util.MD5Encode(sign).toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            log.error(e, e);
        }
        return null;
    }

    //下单
    public static String order(String url, Map<String, Object> map, String privateKey) {
        String sign = getSign(map, privateKey);
        map.put("sign", sign);
        String json = new Gson().toJson(map);
        try {
            String res = doPost(url, json);
            log.info("adjPay下单请求完成");
            return res;
        } catch (IOException e) {
            log.error(e, e);
        }
        return null;
    }

    //下单成功回调通知
    public static String callback() {
        return null;
    }

    public static boolean verifySign(Map<String, Object> map, String publicKey) {
        String sign = (String) map.remove("sign");
        String signVerify = getSign(map, publicKey);
        log.info("sign:" + sign + " signVerify:" + signVerify);
        assert signVerify != null;
        return signVerify.equals(sign);
    }

    public static String doPost(String url, String json) throws IOException {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringEntity s = new StringEntity(json);
        s.setContentEncoding("UTF-8");
        s.setContentType("application/json");//发送json数据需要设置contentType
        post.setEntity(s);
        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return EntityUtils.toString(res.getEntity());// 返回json格式：
        }
        return null;
    }

}
